<template>
  <div class="player-room-bg">
    <div class="player-room-content">
      <div class="game-area">
        <!-- 左侧：房间列表 -->
        <div class="room-list-area">
          <div class="room-list-title">房间列表</div>
          <ul class="room-list">
            <li v-for="room in roomList" :key="room.id" class="room-item">
              <span>{{ room.name }}</span>
              <el-button size="mini" @click="joinRoom(room.id)">进入</el-button>
            </li>
          </ul>
        </div>
        <!-- 右侧：创建房间 -->
        <div class="create-room-area">
          <div class="create-room-title">创建新房间</div>
          <el-input v-model="newRoomName" placeholder="输入房间名" size="small" style="margin-bottom:10px;" />
          <el-button type="primary" size="small" @click="createRoom">创建房间</el-button>
        </div>
      </div>
      <div class="chat-area">
        <!-- 用户信息区域 -->
        <div class="chat-half user-info">
          <div class="user-info-content">
            <div class="user-avatar">
              <img :src="user.avatar || require('@/assets/player-room/avatar.jpg')" alt="头像" />
            </div>
            <div class="user-detail">
              <div class="user-name">用户名：{{ user.name }}</div>
              <div class="user-chips">筹码：{{ user.chips }}</div>
            </div>
          </div>
        </div>
        <!-- 系统消息/聊天区域，仅保留输入框和发送按钮 -->
        <div class="chat-half sys-msg">
          <div class="sys-msg-content">
            <div class="msg-input-bar">
              <input
                v-model="msgInput"
                @keyup.enter="sendMsg"
                type="text"
                placeholder="输入消息并回车或点击发送"
                class="msg-input"
              />
              <button class="msg-send-btn" @click="sendMsg">发送</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'PlayerRoom',
  data() {
    return {
      user: {
        name: '',
        chips: 0,
        avatar: ''
      },
      msgInput: '',
      ws: null,
      roomList: [],
      newRoomName: ''
    }
  },
  mounted() {
    // 获取用户信息
    // fetch('/api/user-info')
    //   .then(res => res.json())
    //   .then(data => {
    //     this.user = data
    //   })
    //   .catch(() => {
    //     this.user = {
    //       name: '张三',
    //       chips: 88888,
    //       avatar: ''
    //     }
    //   })
    // 获取房间列表
    this.fetchRoomList()
    // 建立 WebSocket 连接
    this.ws = new WebSocket('ws://localhost:1314')
    this.ws.onopen = () => {
      // 可选：连接成功提示
       console.log('已连接至服务器')
    }
    this.ws.onmessage = (event) => {
      let msg;
      try {
        msg = JSON.parse(event.data)
        // 处理 JSON 格式的消息
        if (msg.type === 'roomList') {
          this.roomList = msg.list
        }
        // ...其他 JSON 消息处理...
      } catch (e) {
        // 不是 JSON 格式，按字符串处理
        if (event.data.startsWith('CONNECTED|')) {
          // 处理连接成功等自定义消息
          console.log('WebSocket连接成功:', event.data)
        } else {
          console.warn('收到未知格式消息:', event.data)
        }
      }
    }
    this.ws.onclose = () => {
      // 可选：连接关闭提示
      console.log('与服务器的连接已关闭')
    }
    this.ws.onerror = (err) => {
      // 可选：连接错误提示
      // console.error('WebSocket连接错误', err)
    }
  },
  methods: {
    fetchRoomList() {
      // 假设的 API 接口，实际根据后端接口调整
      // fetch('/api/room-list')
      //   .then(res => res.json())
      //   .then(data => {
      //     this.roomList = data
      //   })
      //   .catch(err => {
      //     console.error('获取房间列表失败', err)
      //   })
    },
    sendMsg() {
      const text = this.msgInput.trim()
      if (!text) return
      if (this.ws && this.ws.readyState === 1) {
        this.ws.send(JSON.stringify({
          user: this.user.name || '我',
          text
        }))
      } else {
        this.$message ? this.$message.error('消息发送失败，未连接到服务器') : alert('消息发送失败，未连接到服务器')
      }
      this.msgInput = ''
    },
    joinRoom(roomId) {
      // 进入房间逻辑
      this.$message.success('进入房间 ' + roomId)
    },
    createRoom() {
      if (!this.newRoomName.trim()) {
        this.$message.warning('请输入房间名')
        return
      }
      if (this.ws && this.ws.readyState === 1) {
        this.ws.send(JSON.stringify({
          type: 'createRoom',
          name: this.newRoomName
        }))
        this.newRoomName = ''
        // 等待 ws 推送新的 roomList
      }
    }
  }
}
</script>

<style scoped>
.player-room-bg {
  width: 100vw;
  height: 100vh;
  background: url('@/assets/player-room/player-room-bg.jpg') no-repeat center center;
  background-size: cover;
  display: flex;
  flex-direction: column;
}

.player-room-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.game-area {
  flex: 7;
  display: flex;
  align-items: stretch;
  justify-content: center;
  gap: 32px;
}

.room-list-area, .create-room-area {
  background: rgba(255,255,255,0.92);
  border-radius: 12px;
  padding: 24px 18px;
  min-width: 220px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.room-list-title, .create-room-title {
  font-weight: bold;
  font-size: 1.1rem;
  margin-bottom: 12px;
}

.room-list {
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
}

.room-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  width: 100%;
}

.create-room-area {
  flex: 1;
  padding: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 聊天区域样式 */
.chat-area {
  flex: 3;
  background: rgba(255,255,255,0.85);
  border-top-left-radius: 24px;
  border-top-right-radius: 24px;
  box-shadow: 0 -2px 12px rgba(0,0,0,0.08);
  display: flex;
  align-items: stretch;
  justify-content: center;
  height: 0;
  min-height: 0;
}

.chat-half {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #e0e0e0;
}

.chat-half:last-child {
  border-right: none;
}

.user-info-content {
  display: flex;
  align-items: center;
  gap: 18px;
}

.user-avatar img {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: #eee;
  object-fit: cover;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 8px;
  font-size: 1.1rem;
  color: #333;
}

/* 系统消息/聊天区域样式 */
.sys-msg-content {
  display: flex;
  flex-direction: column;
  width: 90%;
  height: 90%;
  max-width: 400px;
  max-height: 80px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(74,108,247,0.06);
  padding: 16px 12px;
  justify-content: center;
}

.msg-input-bar {
  display: flex;
  align-items: center;
  gap: 8px;
}

.msg-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 1rem;
  outline: none;
}

.msg-send-btn {
  padding: 8px 18px;
  background: linear-gradient(90deg, #4a6cf7 0%, #67c23a 100%);
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: bold;
  cursor: pointer;
  transition: background 0.2s;
}

.msg-send-btn:hover {
  background: linear-gradient(90deg, #67c23a 0%, #4a6cf7 100%);
}

.game-placeholder {
  color: #fff;
  font-size: 2rem;
  font-weight: bold;
  text-shadow: 0 2px 8px rgba(0,0,0,0.25);
}
</style>